<template>
  <div>
    <TopFilter ref="bottomFilter" :list="inputDate1" :cols="3" :collapse="true" @filterChange="changeHandle1" @onCollapse="collapseHandle1"></TopFilter>
    <FilterTable
      ref="table"
      height="300"
      :columns="columns1"
      :fetchapi="fetchApiDetail"
      :isSelectColumn="true"
      selectionType="single"
      :params="fetchParams1"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns1 = columns)"
      :isExportExcel="true"
      exportFileName="配件流水账.xlsx"
      :onCalcExportData="exportHandle"
      :onRowSelectChange="searchDetail"
    >
      <template slot="controls">
        <el-button type="primary" :loading="exportBtnLoading" icon="el-icon-download" @click="handleaPullOut">打印</el-button>
      </template>
    </FilterTable>
    <BasePrint ref="inventoryPrint" :data="printDataInfo" template="templatepartInventory" />
    <BasePrint ref="allInprint" :data="printDataInfo" template="templatepartAllocateIn" />
    <BasePrint ref="allOutPrint" :data="printDataInfo" template="templateAllocateOut" />
    <BasePrint ref="repairMaterialsPrint" :data="printDataInfo" destroyOnClose template="templateRepairMaterials" />
    <BasePrint ref="repairMaterialsPrintExit" :data="printDataInfo" destroyOnClose template="templateRepairMaterialsExit" />
    <BasePrint ref="salesPrint" :data="printDataInfo" template="templateOut" />
    <BasePrint ref="internalPrint" :data="printDataInfo" template="templateInternalReceive" />
    <BasePrint ref="profitPrint" :data="printDataInfo" template="templatePartOverFlow" />
    <BasePrint ref="lossPrint" :data="printDataInfo" template="templatePartBreak" />

    <!-- <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BrandModal :type="handleType" :rowData="formData" @close="closeHandler" />
    </BaseDialog> -->
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { printData, stockIn } from '@/api/part/partInventory/partInventory/index.js';
import {
  searchPartWaterByDto,
  searchPartWaterDetail,
  exportData,
  allInprint,
  allOutPrint,
  queryPrintDataByRoNoOutStockNo,
  getExitPart,
  getOutStockNo,
  salesPrint,
  internalPrint,
  getInternalId,
  getProfitItem,
  searchPartLoss
} from '@/api/part/partOther/partWaterBook';
// import BrandModal from './tabs/brandModal';
import { isAuthorized, arrayObjDeWeight, setRound } from '@/utils/index';
import { getEmployeeInfo } from '@/api/common/auth/employeeAuth';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import moment from 'moment';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { findStorageCode } from '@/api/common/auth/roleManage/index.js';
import { notifyAction } from '../../../../utils';
import { getUser } from '@/assets/js/auth';
import { getOrgByOrgType } from '@/api/part/partOutbound/internalReceive/index';

export default {
  name: 'Brand',
  // components: {
  //   BrandModal
  // },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      js: {
        partNo: '',
        storageCodeName: ''
      },
      topFilterList: this.createTopFilterList(),
      inputDate1: this.inputDate(),
      fetchParams: { xhrAbort: true },
      fetchParams1: { xhrAbort: true },
      visible: false,
      dialogTitle: '',
      fetchApi: searchPartWaterByDto,
      fetchApiDetail: searchPartWaterDetail,
      columns: this.createTableColumns(),
      columns1: this.createTableColumns1(),
      handleType: '',
      formData: {},
      allUsers: {},
      orgDataList: [],
      selectList: [],
      printDataInfo: {},
      serviceAdvisorData: [],
      storageName: [],
      searchBeginDate: moment(new Date().setDate(1)).format('YYYY-MM-DD') + ' 00:00:00',
      nowTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      exportBtnLoading: false // 导出按钮是否加载
    };
  },
  mounted() {
    this.getQueryBookingInformation();
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getStorageList();
    // this.searchBeginDate.setDate(1);
    this.inputDate1[this.findIndex(this.inputDate1, 'start|end')].initialValue = [this.searchBeginDate, this.nowTime];
    this.getOrgByOrgType();
  },
  methods: {
    // 导出行数据处理
    exportHandle(row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          let element = row[key];
          if (!isNaN(row[key])) {
            if (key == 'license') {
              return;
            } else if (key == 'index') {
              return;
            } else if (key == 'customerName') {
              return;
            }
            row[key] = Number(row[key]).toFixed(2);
          }
        }
      }
    },
    findIndex(arr, fieldName) {
      let indexR = -1;
      arr.forEach((x, index) => {
        if (x.fieldName == fieldName) {
          indexR = index;
        }
      });
      return indexR;
    },
    inputDate() {
      return [
        {
          type: 'RANGE_DATE',
          label: '查看日期',
          fieldName: 'start|end',
          placeholder: '查看日期',
          dateType: 'daterange'
        },
        {
          type: 'SELECT',
          label: '进出类型',
          fieldName: 'inOutType',
          filterable: true,
          placeholder: '请输入...',
          itemList: this.createDictList(8249, [82491008, 82491025, 82491026, 82491027, 82491028, 82491029, 82491018, 82491016, 82491017, 82491003, 82491012, 82491024, 82491015])
        },
        {
          type: 'SELECT',
          label: '出入库类型',
          fieldName: 'inOutTag',
          filterable: true,
          placeholder: '请输入...',
          itemList: [
            { text: '出库', value: 10041001 },
            { text: '入库', value: 10041002 }
          ]
        },
        {
          type: 'INPUT',
          label: '单据号码',
          fieldName: 'sheetNo'
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          placeholder: '请输入...',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '请输入...'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '经销商简称',
        //   dataIndex: 'ownerCode',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '仓库',
          dataIndex: 'storageCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.getStorageName(props.row.storageCode)}</span>;
          },
          showOverflowTooltip: true
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '计量单位',
          dataIndex: 'unitName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '库存数量',
          dataIndex: 'stockQuantity',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '锁定数量',
          dataIndex: 'lockedQuantity',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        // {
        //   title: '借入数量',
        //   dataIndex: 'borrowQuantity',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '可用库存',
          dataIndex: 'useableStock',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '最新入库日期',
          dataIndex: 'lastStockIn',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        },
        {
          title: '最新出库日期',
          dataIndex: 'lastStockOut',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'storageCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.getStorageName(props.row.storageCode)}</span>;
          },
          showOverflowTooltip: true
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '发生日期',
          dataIndex: 'operateDate',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'date-range',
          showOverflowTooltip: true
        },
        {
          title: '进出类型',
          dataIndex: 'inOutType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8249', [82491008, 82491025, 82491026, 82491027, 82491028, 82491029, 82491018, 82491016, 82491017, 82491003, 82491012, 82491015]),
          dictItems: this.createDictList('8249'),
          render: (props, h) => {
            return <span> {this.createDictText(props.row.inOutType, '8249')} </span>;
          },
          showOverflowTooltip: true
        },
        {
          title: '进数量',
          dataIndex: 'stockInQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出数量',
          dataIndex: 'stockOutQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入不含税单价',
          dataIndex: 'inOutNetPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入不含税金额',
          dataIndex: 'inOutNetAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入库含税单价',
          dataIndex: 'inOutTaxedPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '出入库含税金额',
          dataIndex: 'inOutTaxedAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '入账后库存数量',
          dataIndex: 'stockQuantity',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '含税成本单价',
          dataIndex: 'costPrice',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '含税成本金额',
          dataIndex: 'costAmount',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '单据号码',
          dataIndex: 'sheetNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '操作员',
          dataIndex: 'createdBy',
          sorter: true,
          filterType: 'input',
          dictItems: [],
          render: props => {
            return <span>{this.getEmployeeName(props.row.createdBy)}</span>;
          },
          showOverflowTooltip: true
        }
      ];
    },
    searchDetail(val) {
      if (val.length > 0) {
        this.selectList = val;
      }
    },
    async getQueryBookingInformation() {
      let res = await getAllUser();
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      // 导出翻译人名
      this.columns1.find(x => x.dataIndex == 'createdBy').dictItems = this.serviceAdvisorData;
      let userList = res.data.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
      this.allUsers = userList;
    },
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      return item ? item.text : '';
    },
    getStorageName(storageCode) {
      const item = this.storageName.find(x => {
        return x.value == storageCode;
      });
      return item ? item.text : '';
    },
    inOutQuantity(val) {
      if (val == null) return 0.0;
      else return val;
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    // searchDetail(row) {
    //   if (row.length > 0) {
    //     this.js = row[0];
    //   }
    // },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    collapseHandle1() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async searchHandle() {
      let data = await this.$refs.bottomFilter.GET_FORM_DATA();
      let val = {
        start: data[1].start,
        end: data[1].end,
        inOutType: data[1].inOutType
      };
      console.log(val, 'bottomFilter');
      this.changeHandle1(val);
    },
    changeHandle1(val) {
      if (val.start) {
        val.start = moment(val.start).format('YYYY-MM-DD');
      }
      if (val.end) {
        val.end = moment(val.end).format('YYYY-MM-DD');
      }
      let data = {
        start: val.start,
        end: val.end,
        inOutType: val.inOutType,
        storageCodeName: this.js.storageCode,
        isAll: 1,
        sheetNo: val.sheetNo,
        inOutTag: val.inOutTag
      };
      this.fetchParams1 = Object.assign({}, data);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}品牌`;
      this.visible = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async getStorageList() {
      // let resdata = await findAllRepair();
      let res = (await findStorageCode()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.storageName = res;
      let res1 = (await getStroageList()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      // this.topFilterList.find(item => item.fieldName === 'storageCode').initialValue = resdata.data['1100'];
      this.topFilterList.find(item => item.fieldName === 'storageCode').itemList = res1;
    },
    // 获取部门字典
    async getOrgByOrgType() {
      const res = await getOrgByOrgType({ orgType: '15061001,15061002,15061003,15061004,15061005,15061006,15061007,15061008,15061009,15061010,15061011,15061012,15061013,15061014,15061015' });
      console.log(res, 'ressss');
      let data = arrayObjDeWeight(res.data, 'orgId');
      // this.receiptorList = res.data;
      this.orgDataList = data.map(x => ({ text: x.orgName, value: x.orgId + '' }));
    },
    // 点击打印
    async handleaPullOut() {
      console.log(this.selectList, 'this.selectList::');
      if (this.selectList.length <= 0) {
        notifyAction('请选中一条数据', 'warrning');
        return;
      }
      if (this.exportBtnLoading) return;
      let inOutType = this.selectList[0].inOutType;
      let orderNo = this.selectList[0].sheetNo;
      let outQuantity = this.selectList[0].stockOutQuantity;
      let itemId = this.selectList[0].repairPartId;
      let res = {};
      let printObject = '';
      this.exportBtnLoading = true;
      switch (inOutType) {
        case 82491001: //采购入库
          const resId = await stockIn({ stockInNo: orderNo, isFinished: 1 });
          let cunPrintid = resId.data.rows[0].PART_BUY_ID;
          res = await printData(cunPrintid, 0);
          printObject = this.$refs.inventoryPrint;
          break;
        case 82491002: //调拨入库
          let isFlow = { isFlow: 1 };
          res = await allInprint(orderNo, 0, isFlow);
          printObject = this.$refs.allInprint;
          break;
        case 82491005: //配件报溢
          res = await getProfitItem({ profitNo: orderNo });
          res.profitNo = orderNo;
          let userId = await getUser();
          console.log('userId:', userId);
          res.USER_NAME = userId || '';
          res.data[0].CREATED_NAME = this.serviceAdvisorData.find(item => item.value == res.data[0].CREATED_BY).text || '';
          let a = JSON.parse(JSON.stringify(res));
          res.data = a;
          printObject = this.$refs.profitPrint;
          console.log(res, 'res:::');
          break;
        case 82491006: //维修发料
          const outStockNoRes = await getOutStockNo({ itemId });
          let outStockNo = outStockNoRes.data;
          if (outQuantity > 0) {
            res = await queryPrintDataByRoNoOutStockNo({ roNo: orderNo, outStockNo });
            printObject = this.$refs.repairMaterialsPrint;
          } else {
            res = await getExitPart({ roNo: orderNo, outStockNo });
            printObject = this.$refs.repairMaterialsPrintExit;
          }
          if (res.data) {
            let serviceAdvisor = this.allUsers.find(item => res.data.SERVICE_ADVISOR == item.value);
            let chiefTechnician = this.allUsers.find(item => res.data.CHIEF_TECHNICIAN == item.value);
            res.data.SERVICE_ADVISOR = serviceAdvisor ? serviceAdvisor.text : res.data.SERVICE_ADVISOR;
            res.data.CHIEF_TECHNICIAN = chiefTechnician ? chiefTechnician.text : res.data.CHIEF_TECHNICIAN;

            let sender = this.allUsers.find(item => res.data.SENDER == item.value);
            let receiver = this.allUsers.find(item => res.data.RECEIVER == item.value);
            res.data.SENDER = sender ? sender.text : res.data.SENDER;
            res.data.RECEIVER = receiver ? receiver.text : res.data.RECEIVER;
          }
          // 翻译发料人和领料人
          if (res.data && res.data.items.length) {
            res.data.items.forEach(x => {
              let sender = this.allUsers.find(item => x.SENDER == item.value);
              let receiver = this.allUsers.find(item => x.RECEIVER == item.value);
              x.SENDER = sender ? sender.text : x.SENDER;
              x.RECEIVER = receiver ? receiver.text : x.RECEIVER;
            });
          }
          break;
        case 82491007: //配件销售
          res = await salesPrint(orderNo);
          res.data.baseInfo.USER_NAME = this.serviceAdvisorData.find(item => item.value == res.data.baseInfo.USER_ID).text || '';
          res.data.baseInfo.CREATED_NAME = this.serviceAdvisorData.find(item => item.value == res.data.baseInfo.CREATED_BY).text || '';
          if (res.data.baseInfo.SALES_PART_AMOUNT) {
            res.data.baseInfo.SALES_PART_AMOUNT = setRound(res.data.baseInfo.SALES_PART_AMOUNT);
          }
          printObject = this.$refs.salesPrint;
          break;
        case 82491009: //内部领用
          let params = {};
          params.ids = itemId;
          let internalIdRes = await getInternalId({ orderNo });
          let name = '';
          res = await internalPrint(internalIdRes.data, params);
          this.serviceAdvisorData.forEach(x => {
            if (res.data.baseInfo.USER_ID == x.value) {
              res.data.baseInfo.USER_NAME = x.text;
            }
            if (res.data.baseInfo.RECEIPTOR == x.value) {
              res.data.baseInfo.RECEIPTOR_USER = x.text;
            }
            if (res.data.detailInfo[0].UPDATED_BY == x.value) {
              name = x.text;
            }
            res.data.baseInfo.RECEIPTOR_NAME = this.orgDataList.find(item => item.value == res.data.baseInfo.ORG_CODE).text;
            res.data.detailInfo[0].UPDATED_BY_USER = name;
          });
          printObject = this.$refs.internalPrint;
          break;
        case 82491010: //调拨出库
          res = await allOutPrint(orderNo, 0);
          printObject = this.$refs.allOutPrint;
          break;
        case 82491011: //借出登记
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491004: //借出归还
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491013: //配件移库出库
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491014: //配件报损
          res = await searchPartLoss({ lossNo: orderNo, isPrint: 1 });
          let item = JSON.parse(JSON.stringify(res.data));
          let handlerName = this.serviceAdvisorData.find(x => x.value == item[0].HANDLER).text;
          let userName = getUser();
          res.data = {
            lossNo: orderNo,
            handler: handlerName,
            lossDate: item[0].LOSS_DATE,
            items: item,
            USER_NAME: userName
          };
          printObject = this.$refs.lossPrint;
          break;
        case 82491019: //成本价调整入库
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491020: //成本价调整出库
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491021: //发料价格调整入库
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491022: //发料价格调整出库
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491030: //借用报损
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491031: //库存报损
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
        case 82491023: //配件移库入库
          notifyAction('该类型出入库无法打印', 'warrning');
          break;
      }
      if (res.resultCode == 200) {
        this.printDataInfo = res.data;
      }
      console.log(this.printDataInfo, 'this.printDataInfo::');
      // let queryData = (await this.$refs.bottomFilter.GET_FORM_DATA())[1];
      // queryData.start = queryData.start ? moment(queryData.start).format('YYYY-MM-DD') : '';
      // queryData.end = queryData.end ? moment(queryData.end).format('YYYY-MM-DD') : '';
      // let data = {
      //   // ...queryData,
      //   start: queryData.start,
      //   end: queryData.end,
      //   partNo: this.js.partNo,
      //   storageCodeName: this.js.storageCode
      // };
      // let res = await exportData(data);
      this.$nextTick(() => {
        if (printObject != '') {
          console.log('printObject::', printObject);
          printObject.EXCUTE_PRINT();
        }
      });
      this.exportBtnLoading = false;
      // exportExcelFile(res.data, this.js.partName + '在仓库' + this.getStorageName(this.js.storageCode) + '中流水账导出');
    }
  }
};
</script>

<style lang="less" scoped></style>
